﻿using System.Collections.Generic;
using System.Linq;
using SeaBattle.Domain.Abstract;
using SeaBattle.Domain.Abstract.Services;
using SeaBattle.Domain.Entities;
using SeaBattle.Domain.Factory;

namespace SeaBattle.Domain.Concrete.Services
{
    public class GameService : IGameService
    {
        private readonly IGameRepository _gameRepository;

        public GameService()
        {
            if (_gameRepository == null)
            {
                _gameRepository = GameFactory.GameRepository;

            }
        }

        public Game CreateNewGame(string name, int preset, Player creator)
        {
            var game = _gameRepository.CreateNewGame(name,creator);
            game.Preset = preset;
            _gameRepository.SaveGame(game);
            return game;
        }

        public IEnumerable<Game> GetGames()
        {
            return _gameRepository.GetAllGames()
                .OrderBy(x => x.Preset)
                .Select(x => x);
        }

        public Game GetGameById(int gameId)
        {
            return _gameRepository.GetAllGames().Single(x => x.Id == gameId);
        }

        public IEnumerable<Game> GetParticipantsPlayerGames(Player player)
        {
            return from x in _gameRepository.GetAllGames()
                   where x.Creator == player
                   orderby x.Created descending
                   select x;
        }
    }
}
